package org.squabble.dao;

import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.squabble.domain.Article;

@Repository
public class ArticleDAOImpl extends AbstractHibernateDAO<Article> implements
		ArticleDAO {
	private final Log log = LogFactory.getLog(this.getClass());

	@Autowired
	public ArticleDAOImpl(SessionFactory sessionFactory) {
		super(Article.class, sessionFactory);
	}

	@Override
	public void saveArticle(Article article) {
		currentSession().saveOrUpdate(article);
	}

	@Override
	public List<Article> getArticles() {
		Criteria criteria = criteria();
		criteria.addOrder(Order.desc("id"));
		List<Article> articles = list(criteria);
		log.debug("Returning " + articles.size() + " articles");
		return articles;
	}

	@Override
	public Article getArticle(Long id) {
		return get(id);
	}

	@Override
	public void delete(Article article) {
		this.delete(article);

	}

	@Override
	public Article load(Long articleId) {
		return this.load(articleId);
	}

	@Override
	public List<Article> getLatestArticles(int dispCount) {
		Criteria criteria = this.criteria();
		criteria.add(Restrictions.le("displayDate", new Date()));
		criteria.addOrder(Order.desc("displayDate"));
		criteria.setMaxResults(dispCount);
		return this.list(criteria);
	}
}
